package com.an.nopro.app;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * 
* @ClassName: DataSourceConfig
* @Description: TODO(多数据源配置)
* @author antch,861710865@qq.com
* @date 2017年8月7日 下午4:03:06
*
 */

//@Configuration
//制定分库的mapper地址
//@MapperScan(basePackages= {"com.an.nopro.mapper.spring"},sqlSessionTemplateRef="testSqlSessionTemplate")
public class DataSourceConfig {

	//1、创建DataSource
	@Bean(name="testDatasource")
	@ConfigurationProperties(prefix="spring.datasource.spring")
	public DataSource testDatasourec() {
		System.out.println("创建数据源");
		return DataSourceBuilder.create().build();
	}
	
	
	//2、再创建SqlSessionFactory
	@Bean(name="testSqlSessionFactory")
	@Primary
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDatasource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
		return bean.getObject();
	}
	
	//3、创建事务
	@Bean(name="testTransactionManager")
	@Primary
	public DataSourceTransactionManager testTransactionManager(@Qualifier("testDatasource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
	
	//4、最后包装到SqlSessionTemplate
	@Bean(name = "testSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
